class_name Player
extends CharacterBody2D

# -----------------------变量声明------------------------- # 
signal healthChanged
@onready var effect = $Effect
@onready var animation = $AnimationPlayer
@onready var hurtBox = $HurtBox
@export var speed := 35
@export var maxHealth = 3
@onready var health = maxHealth:
@onready var effect = $Effect
@onready var animation = $AnimationPlayer
@onready var hurtBox = $HurtBox
@onready var weapon = $武器
@export var speed := 35
@export var maxHealth = 3
@onready var health = maxHealth:
	set(v):
		if v == health or v < 0 or v > maxHealth: return
		health = v
		healthChanged.emit(health)
@export var knockbackPower: int = 500
@export var bag: Bag

var isHurt: bool = false
var isAttack: bool = false
var dir := '向下'

# -----------------------生命周期------------------------- # 
func _physics_process(_delta: float) -> void:
	move()
	updateAnimation()
	checkEnemy()

# -----------------------响应函数------------------------- # 
# 处理用户输入
func handleInput():
	var movement = Input.get_vector('ui_left', 'ui_right', 'ui_up', 'ui_down')
	velocity = movement * speed
	move_and_slide()
	if Input.is_action_just_pressed('攻击'):
		attack()

# 更新动画
func updateAnimation():
	if isAttack: return
	if velocity.length() == 0: animation.stop(); return
	dir = '向下'
	if velocity.y < 0: dir = '向上'
	if velocity.x < 0: dir = '向左'
	elif velocity.x > 0: dir = '向右'
	animation.play(dir + '走')

# 检索敌人
func checkEnemy():
	if isHurt: return
	for area in hurtBox.get_overlapping_areas():
		if area.name == 'HitBox':
			hurt(area)

# 攻击
func attack():
	animation.play(dir + '攻击')
	weapon.enable()
	isAttack = true
	await animation.animation_finished
	isAttack = false
	weapon.disable()

# 受伤
func hurt(area: Area2D):
	health -= 1
	if health == 0: return death()
	isHurt = true
	knockback(area.get_parent().velocity)
	flash()

# 击退--敌人的方向减去自己的方向
func knockback(enemyVelocity: Vector2):
	var direc = (enemyVelocity - velocity).normalized() * knockbackPower
	velocity = direc
	move_and_slide()

# 闪烁
func flash():
	effect.play('受伤')
	await get_tree().create_timer(1).timeout
	effect.play('RESET')
	isHurt = false

func death():
	get_tree().reload_current_scene()
